package cn.itcast.tanhua.mytanhuadubboservice.api;

import cn.itcast.tanhua.enums.CommentType;
import cn.itcast.tanhua.mytanhuadubbointerface.api.MessageApi;
import cn.itcast.tanhua.pojo.Comment;
import cn.itcast.tanhua.vo.PageInfo;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author 郭文亮
 * @since 2021/12/2 16:48
 */
@Service
public class MessageApiImpl implements MessageApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PageInfo<Comment> queryLikeCommentListByUser(Long publishUserId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(publishUserId, CommentType.LIKE, page, pageSize);
    }


    @Override
    public PageInfo<Comment> queryCommentListByUser(Long publishUserId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(publishUserId, CommentType.COMMENT, page, pageSize);
    }

    @Override
    public PageInfo<Comment> queryLoveCommentListByUser(Long publishUserId, Integer page, Integer pageSize) {
        return this.queryCommentListByUser(publishUserId, CommentType.LOVE, page, pageSize);
    }

    private PageInfo<Comment> queryCommentListByUser(Long publishUserId, CommentType commentType, Integer page, Integer pageSize) {
        // 创建结果集pageResult
        PageInfo<Comment> pageInfo = new PageInfo<>();

        // 通过publishUserId查询被点赞过的信息
        PageRequest pageRequest = PageRequest.of(page-1,pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("publishUserId").is(publishUserId)
                .and("commentType").is(commentType.getType()))
                .with(pageRequest);
        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);

        // 封装结果集数据
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);

        return pageInfo;
    }

}
